<template>
  <div class="app-container table-app-container">
    <div class="fixed-table">
      <PageableTable
        ref="table"
        :loading="false"
        :data="tableData"
        :table-height="500"
        :row-class-name="tableRowClassName"
        :disable-pageable="true"
        :multiple-selected="true"
        class="fixed-table-table"
        @selection-change="onSelectionChange"
      >
        <el-table-column v-for="column in insideColumns" :key="column.key" :label="column.title" :prop="column.key" :sortable="column.sortable">
          <template slot-scope="scope">
            <column-render :render="column.render" :row="scope.row" :column="column" />
          </template>
        </el-table-column>
      </PageableTable>
    </div>
  </div>
</template>

<script>
import PageableTable from '@neu/biz-core/components/PageableTable'
import databind from '@neu/biz-core/mixins/databind'
import { detail as instanceDetail, updateAttr } from '@neu/dcom-ui/api/instance'
import { detail as schemaDetail } from '@neu/dcom-ui/api/schema'
import { deepClone, parseTime } from '@neu/biz-core/utils'

export default {
  name: 'CmdbInstanceAttrForm',
  components: {
    PageableTable
  },
  mixins: [databind],
  props: {
    instanceId: {
      required: true,
      type: String
    },
    forSelection: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      requestLoading: false,
      instance: {
        name: '',
        schemadef: {
          _id: '',
          name: ''
        },
        attrs: {}
      },
      editKey: '',
      cloneAttrs: {},
      schemaAttrs: [],
      tableData: [],
      insideColumns: [
        { title: '属性名称', key: 'name' },
        { title: '属性值', key: 'value' }
      ]
    }
  },
  created() {
    this.fetch()
  },
  methods: {
    // 获取实例详细信息
    fetch: function() {
      this.requestLoading = true
      instanceDetail(this.instanceId).then(response => {
        const data = response.data
        this.tableData = Object.entries(deepClone(data)).map(e => {return {key: e[0], name: e[0], value: e[1]}})
        return
        const _attrs = response.data.attrs
        const attrs = _attrs.reduce((o, item) => { o[item.key] = item.value; return o }, {})
        this.cloneAttrs = deepClone(attrs)

        schemaDetail(response.data.schemadef._id).then(response2 => {
          const instance = { ...response.data, attrs, schemadef: response2.data }
          this.instance = instance
          let schemaAttrs = response2.data.attrs
          const categoryAttrs = response2.data.category.attrs || []
          schemaAttrs = [...schemaAttrs, ...categoryAttrs]

          this.schemaAttrs = Object.freeze(schemaAttrs)
          this.requestLoading = false

          // console.log(this.instance)

          // const fixedItem = [
          //   { 'name': 'ID', 'value': this.instance._id, disableRow: true },
          //   { 'name': '唯一标识', 'value': this.instance.code, disableRow: true },
          //   { 'name': '名称', 'value': this.instance.name, disableRow: true },
          //   { 'name': '所属模型', 'value': this.instance.schemadef.name, disableRow: true }
          // ]

          // this.tableData.push(...fixedItem)

          const data = []
          for (const key in instance.attrs) {
            const item = {}
            item.key = key
            item.name = this.getAttrName(key)
            item.value = this.getAttrValue(key, instance.attrs[key])
            data.push(item)
          }
          this.tableData = deepClone(data)
        })
      })
    },

    // 从模型定义中获取属性名称
    getAttrName(k) {
      const attr = this.schemaAttrs.find(it => it.field === k)
      return attr ? attr.name : k
    },

    // 获取格式化属性值
    getAttrValue(k, v) {
      const attr = this.schemaAttrs.find(it => it.field === k)
      if (attr.dtype === 'date') {
        return parseTime(v)
      } else if (attr.dtype === 'enum') {
        const enumItem = attr.enums.find(e => e.value === v)
        return enumItem ? enumItem.label : ''
      } else if (attr.dtype === 'bool') {
        return v ? '是' : '否'
      }
      return v !== null ? v : '未设置'
    },

    // 获取属性原始值，判断属性值是否改变
    getOriginalAttrVal(k) {
      return this.cloneAttrs[k]
    },

    // 设置属性为编辑状态
    onEditAttr(k) {
      this.editKey = k
    },

    // 取消属性的编辑状态
    onCancelEditAttr(k) {
      this.editKey = ''
      this.instance.attrs[k] = this.getOriginalAttrVal(k)
    },

    // 提交单个属性值的改变
    onSaveAttr(k) {
      updateAttr(this.instanceId, k, this.instance.attrs[k]).then(response => {
        this.cloneAttrs[k] = this.instance.attrs[k]
        this.editKey = ''
      })
    },

    // 获取属性的数据类型定义
    getAttrDType(k) {
      const schemaAttr = this.schemaAttrs.find(it => it.field === k)
      return schemaAttr ? schemaAttr.dtype : 'string'
    },

    // 获取枚举属性的枚举项定义
    getEnmuOptions(k) {
      const schemaAttr = this.schemaAttrs.find(it => it.field === k)
      return schemaAttr ? schemaAttr.enums : []
    },

    // 获取数据源属性的数据源定义
    getDatasource(k) {
      const schemaAttr = this.schemaAttrs.find(it => it.field === k)
      return schemaAttr ? schemaAttr.datasource : {}
    },

    // 获取外键属性的定义
    getForeignKey(k) {
      const schemaAttr = this.schemaAttrs.find(it => it.field === k)
      return schemaAttr ? schemaAttr.dvalue : ''
    },

    // 设置行索引
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex
    }
  }
}
</script>

<style lang="scss">
  .instance-attr-form {
    min-height: calc(100vh - 200px);
    .attr-item {
      button {
        display: none;
      }
      &:hover  {
        button {
          display: inline-block;
        }
      }
    }
  }
</style>
